<?php
session_start();
$uri= explode("Service",$_SERVER['REQUEST_URI']);
$final_uri=$_SERVER['HTTP_HOST'].$uri[0];

    if(isset($_GET['code'])) {
        // try to get an access token
        
        $fileGO=fopen("../../google.txt","r") or exit ("do not open setting file!");
        $leggi=@fread($fileGO,filesize("../../google.txt"));
        $dynamic_urlGO=nl2br($leggi);

        if($dynamic_urlGO != null){
                $temp = explode(";",$dynamic_urlGO);
                $id_GO = $temp[0];
                $secret_GO= $temp[1];
            }
        $code = $_GET['code'];
        $url = 'https://accounts.google.com/o/oauth2/token';
        $params = array(
            "code" => $code,
            "client_id" => $id_GO,
            "client_secret" => $secret_GO,
            "redirect_uri" => "http://".$final_uri."Service/Google/google.php/oauth2callback",
            "grant_type" => "authorization_code"
        );

        $request = new HttpRequest($url, HttpRequest::METH_POST);
        $request->setPostFields($params);
        $request->send();
        $responseObj = json_decode($request->getResponseBody());
        
        
       /* echo "Access token: " . $responseObj->access_token;*/
        
        $access_token = $responseObj->access_token;
        
        $url1 =("https://www.googleapis.com/plus/v1/people/me?access_token=".$access_token);
       
        $ch = curl_init($url1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        
        $output=curl_exec($ch);
        curl_close($ch); 
       
        $arr = json_decode($output,true);
        //pendere urlimg
        $urlimg=$arr['image']['url'];
        
        $id_go=$arr['id'];
       
        //echo$urlimg;
        
        ?>
<script type="text/javascript">    
Invia_TokenGP();

function Invia_TokenGP(){
    
    var final_uri ="<?php echo$final_uri; ?>";
   
    location.href= "http://"+final_uri+"Service/insert_token.php?access_token=<?php echo$access_token.";".$id_go; ?>&service=Google&urlimg=<?php echo$urlimg; ?>";
 }
</script>
      <?php
        
    }else{
        $fileGO=fopen("../../google.txt","r") or exit ("do not open setting file!");
        $leggi=@fread($fileGO,filesize("../../google.txt"));
        $dynamic_urlGO=nl2br($leggi);

        if($dynamic_urlGO != null){
                $temp = explode(";",$dynamic_urlGO);
                $id_GO = $temp[0];
                $secret_GO= $temp[1];
            }
        $url = "https://accounts.google.com/o/oauth2/auth";
 
        $params = array(
            "response_type" => "code",
            "client_id" => $id_GO,
            "redirect_uri" => "http://".$final_uri."Service/Google/google.php/oauth2callback",
            "scope" => "https://www.googleapis.com/auth/plus.me"
            );

        $request_to = $url . '?' . http_build_query($params);

        header("Location: " . $request_to);
    }
    //https://www.googleapis.com/plus/v1/people/me?access_token=
?>



